import time
from tqsdk import TqApi, TqAuth, TqKq
from rich.console import Console
from rich.theme import Theme

# 定义颜色主题
custom_theme = Theme({
    "info": "bright_cyan",
    "warning": "bright_yellow",
    "error": "bright_red",
    "success": "bright_green",
    "trade": "bold bright_magenta"
})
console = Console(theme=custom_theme)

if __name__ == "__main__":
    symbol = "SHFE.ni2506"  # 合约代码

    try:
        # 使用当前代码的 API 账号和密码
        api = TqApi(account=TqKq(), auth=TqAuth("cps168", "alibaba"))

        while True:
            # 等待数据更新
            api.wait_update()
            console.print(f"**********{time.strftime('%X')} 未成交委托单查询**********", style="warning")

            # 获取所有订单
            orders = api.get_order()
            for order_id, order in orders.items():
                # 检查 order 是否为订单对象且状态为 ALIVE
                if hasattr(order, 'status') and order.status == "ALIVE":
                    # 打印未成交委托单信息，包含 last_msg
                    console.print(f"订单 ID: {order_id}, 状态: {order.status}, 合约: {order.instrument_id}, 方向: {order.direction}, 开平: {order.offset}, 价格: {order.limit_price}, 数量: {order.volume_orign}, 最新消息: {getattr(order, 'last_msg', '无')}", style="info")
                else:
                    continue  # 跳过非未成交的订单

    except KeyboardInterrupt:
        console.print("用户手动终止程序", style="warning")
    finally:
        # 关闭 API 连接
        api.close()
        console.print("程序已停止", style="info")
